﻿using SharpDepend.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SharpDepend.WPF
{
    internal class ServerManager : ISocketServerManager
    {
        class Server : ISocketServer
        {
            private TcpListener mServer;

            public void Constructor(string ip, int port)
            {
                mServer = new TcpListener(IPAddress.Parse(ip), port);
            }

            public ISocketClient AcceptTcpClient()
            {
                ClientManager.Client client = new ClientManager.Client(mServer.AcceptTcpClient());
                return client;
            }

            public void Start()
            {
                mServer.Start();
            }

            public void Stop()
            {
                mServer.Stop();
            }
        }

        public ISocketServer CreateServer(string ip, int port)
        {
            Server server = new Server();
            server.Constructor(ip, port);
            return server;
        }


        public string LocalIp
        {
            get
            {
                IPHostEntry host;
                string localIP = null;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localIP = ip.ToString();
                        break;
                    }
                }
                return localIP;
            }
        }
    }
}
